package com.dayuanit.booksystem.v4.servlet;

import com.dayuanit.booksystem.v4.domain.BookInfo;
import com.dayuanit.booksystem.v4.service.BookService;
import com.dayuanit.booksystem.v4.service.impl.BookServiceImpl;
import com.dayuanit.booksystem.v4.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 处理图书请求的servlet
 */
public class BookServlet extends BaseServlet {

    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----处理图书-----");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if ("add".equals(action)) {
            add(req, resp);
        }

        if ("queryById".equals(action)) {
            queryById(req, resp);
        }

        if ("queryByName".equals(action)) {
            queryByName(req, resp);
        }
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookName = req.getParameter("bookName");
        String author = req.getParameter("author");
        String price = req.getParameter("price");
        String publisherId = req.getParameter("publisherId");
        bookService.addBook(bookName, author, price, Long.parseLong(publisherId));

        sendResultToClient("添加成功", resp);
    }

    private void queryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    private void queryByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookName = req.getParameter("bookName");
        String author = req.getParameter("author");
        String currentPage = req.getParameter("currentPage");

        //容错性
        if (StringUtils.isBlank(currentPage)) {
            currentPage = "1";
        }

        List<BookInfo> bookInfos = bookService.listBookInfo(author, bookName, null, Integer.parseInt(currentPage));

        //总条数
        int total = bookService.countBookInfo(author, bookName, null);
        //总页数
        int totalPage = total % 2 == 0 ? total / 2 : total / 2 + 1;

        //每页显示的数据
        req.setAttribute("bookInfos", bookInfos);
        //将当前页保存在request
        req.setAttribute("currentPage", currentPage);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("author", author);
        req.setAttribute("bookName", bookName);



        //响应页面
        req.getRequestDispatcher("/WEB-INF/page/v3/book.jsp").forward(req, resp);
    }




}
